package com.rrd.dw.utils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author liubaoxin
 */
public class HadoopUtils {
    private static final Logger log = LoggerFactory
        .getLogger(HadoopUtils.class);

    public static void delete(Configuration conf, Iterable<Path> paths)
            throws IOException {
        if (conf == null) {
            conf = new Configuration();
        }
        for (Path path : paths) {
            FileSystem fs = path.getFileSystem(conf);
            if (fs.exists(path)) {
                log.info("Deleting {}", path);
                fs.delete(path, true);
            }
        }
    }

    public static void delete(Configuration conf, Path... paths)
            throws IOException {
        delete(conf, Arrays.asList(paths));
    }

    public static List<Path> getDirPaths(Configuration conf, Path folderPath) throws IOException {
        List<Path> paths = new ArrayList<>();
        FileSystem fs = folderPath.getFileSystem(conf);
        if (fs.exists(folderPath)) {
            FileStatus[] fileStatus = fs.listStatus(folderPath);
            for (FileStatus fileStatu : fileStatus) {
                if (fileStatu.isDirectory()) {
                    paths.add(fileStatu.getPath());
                }
            }
        }
        if (paths.size() == 0) {
            paths.add(folderPath);
        }
        return paths;
    }

}
